﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text.pdf;
using System.IO;
using System.Text;
using iTextSharp.text;

namespace ProjectStudy.iTextSharpHeader
{
    public class PDFHelper
    {
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="inputfilepath">PDF源路径</param>
        /// <param name="outputfilepath">PDF目标路径</param>
        /// <param name="imgPath">水印图片路径</param>
        /// <param name="top"></param>
        /// <param name="left"></param>
        /// <returns></returns>
        public static bool AddWatermarkImg(string inputfilepath,string pwd, string outputfilepath, string imgPath, float top, float left)
        {
            //throw new NotImplementedException();
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                if (pwd != null && pwd.Length > 0)
                {
                    pdfReader = new PdfReader(inputfilepath, Encoding.UTF8.GetBytes(pwd));
                }
                else
                {
                    pdfReader = new PdfReader(inputfilepath);
                }

                int numberOfPages = pdfReader.NumberOfPages;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;
                float height = psize.Height;

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                PdfContentByte waterMarkContent;

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imgPath);
                image.ScaleAbsolute(50, 50);
                image.GrayFill = 20;//透明度，灰色填充
                //image.Rotation//旋转
                //image.RotationDegrees//旋转角度
                //水印的位置 
                if (left < 0)
                {
                    left = width / 2 - image.Width + left;
                }

                //image.SetAbsolutePosition(left, (height - image.Height) - top);
                image.SetAbsolutePosition(width - 50, 0);

                //每一页加水印,也可以设置某一页加水印 
                for (int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印
                    waterMarkContent.AddImage(image);
                }
                //strMsg = "success";
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }


        /// <summary>
        /// 向已存在PDF文档添加水印、页眉页脚(页码)
        /// </summary>
        /// <param name="inputfilepath">PDF源路径</param>
        /// <param name="pwd">源PDF密码</param>
        /// <param name="outputfilepath">目标路径</param>
        /// <param name="waterMarkName">水印文字</param>
        /// <param name="oddHeader">奇数页眉</param>
        /// <param name="evenHeader">偶数页眉</param>
        /// <param name="isAddPageNum">是否添加页码</param>
        public static void AddWatermarkWordHeaderPageNum(string inputfilepath,string pwd, string outputfilepath, string waterMarkName,string oddHeader,string evenHeader,bool isAddPageNum)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            //获取所用权
            PdfReader.unethicalreading = true;
            try
            {
                if (pwd != null && pwd.Length > 0)
                {
                    pdfReader = new PdfReader(inputfilepath, Encoding.UTF8.GetBytes(pwd)); 
                }
                else
                {
                    pdfReader = new PdfReader(inputfilepath);
                }
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                int total = pdfReader.NumberOfPages;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                for (int i = 1; i <= total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印

                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                   
                    content.BeginText();

                    if (waterMarkName != null && waterMarkName.Length > 0)
                    {
                        content.SetColorFill(BaseColor.LIGHT_GRAY);
                        content.SetFontAndSize(font, 80);
                        content.SetTextMatrix(0, 0);
                        content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
                    }

                    if (oddHeader != null && oddHeader.Length > 0 && evenHeader != null && evenHeader.Length > 0)
                    {
                        gs.FillOpacity = 1f;
                        content.SetGState(gs);
                        content.SetColorFill(BaseColor.RED);
                        content.SetFontAndSize(font, 9);
                        content.SetTextMatrix(0, 0);
                        if (i % 2 == 0)
                        {
                            content.ShowTextAligned(Element.ALIGN_CENTER,evenHeader, width / 2, height - 20, 0);
                        }
                        else
                        {
                            content.ShowTextAligned(Element.ALIGN_CENTER, oddHeader, width / 2, height - 20, 0);
                        }
                    }

                    if (isAddPageNum)
                    {
                        content.SetColorFill(BaseColor.BLACK);
                        content.SetFontAndSize(font, 9);
                        content.SetTextMatrix(0, 0);
                        content.ShowTextAligned(Element.ALIGN_CENTER, String.Format("第{0}页,共{1}页", i, total), width / 2, 20, 0);
                    }

                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }

        /// <summary>
        /// 添加倾斜水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        public static void PDFWatermarkWordItalic(string inputfilepath,string pwd, string outputfilepath, string waterMarkName)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                if (pwd != null && pwd.Length > 0)
                {
                    pdfReader = new PdfReader(inputfilepath, Encoding.UTF8.GetBytes(pwd));
                }
                else
                {
                    pdfReader = new PdfReader(inputfilepath);
                }
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                // 设置密码   
                //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission); 

                int total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                gs.FillOpacity = 0.2f;//透明度

                int j = waterMarkName.Length;
                char c;
                int rise = 0;
                for (int i = 1; i < total; i++)
                {
                    rise = 500;
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印

                    content.BeginText();
                    content.SetColorFill(BaseColor.DARK_GRAY);
                    content.SetFontAndSize(font, 50);
                    // 设置水印文字字体倾斜 开始 
                    if (j >= 15)
                    {
                        content.SetTextMatrix(200, 120);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 20;
                        }
                    }
                    else
                    {
                        content.SetTextMatrix(180, 100);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 18;
                        }
                    }
                    // 字体设置结束 
                    content.EndText();
                    // 画一个圆 
                    //content.Ellipse(250, 450, 350, 550);
                    //content.SetLineWidth(1f);
                    //content.Stroke(); 
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }

                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }
        }
    }
}